/*
 * Created on Jun 13, 2005
 *
 */
package com.erclab.internal.xpresso.formelements;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.dataAccess.GenericResultSet;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.forms.Form;

/**
 * @author Enrique Rodriguez.
 *
 */
public class SimpleTextDisplay extends FormElement {

	protected String lookupValue;

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#toHTML(com.erclab.internal.xpresso.forms.Form, com.erclab.internal.xpresso.forms.FormParameters)
	 */
	public String toHTML(Form theForm) {
		if (theForm.getFormParameters().getAction().equals("update")){
			if(originalValue != null){
				return this.originalValue;
			}
		} else {
			if(lookupValue != null){
				return this.lookupValue;
			}
		}
		return "";
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#loadLookupValues(com.erclab.internal.xpresso.forms.FormParameters)
	 */
	public void loadLookupValues(Form theForm)
		throws FormException {
		if (this.lookupQuery != null && !this.lookupQuery.equals("")){
			ApplicationDataSource ads = Settings.getRepository().getApplicationDataSource(this.lookupDataSourceId);
			if (ads == null){
				throw new FormException("The data source specified by the element does not exist");	
			}
			
			String query = ads.getQueryBuilder().modifyLookupQuery(this.lookupQuery, theForm.getFormParameters());
			GenericResultSet grs = null;
			try {
				grs = ads.runQuery(query);
			} catch (DataSourceException e) {
				throw new FormException("An error ocurred loading form element lookup. Query:" + this.lookupQuery + "; Exception: " + e +" Datasource: " + ads.getDataSourceName());
			}
			
			int lookupResults = grs.getNumberOfRows();
			if (lookupResults > 0){
				// There should be only one result
				while(grs.nextRow()){
					lookupValue = grs.getRow()[0];
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#isModifiable()
	 */
	public boolean isModifiable() {
		// TODO Auto-generated method stub
		return false;
	}

}
